package net.xt.testthread;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class TestSemaphore {

    public static void main(String[] args) throws InterruptedException {
        // 当前任务只允许一个线程进行操作
        Semaphore semaphore = new Semaphore(2, true);

        Thread t1 = new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + " start.");

                // 休眠1分钟
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            try {
                semaphore.acquire();
                System.out.println(Thread.currentThread().getName() + " start.");
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }

            try {
                System.out.println(Thread.currentThread().getName() + " is running.");
            } finally {
                semaphore.release();
            }
        }, "t2");

        t1.start(); // t1启动，休眠1分钟
        t2.start(); // t2启动，获取不到锁，阻塞
        TimeUnit.SECONDS.sleep(2);
        t2.interrupt(); // t2中断后可以拿到锁，如果不释放，后续线程无法获取锁

        // 主线程main获取锁
        semaphore.acquire();
        System.out.println(Thread.currentThread().getName() + " start.");
        semaphore.release();
    }

}
